<!-- DictSelector.vue -->
<template>
  <el-select
    :v-model="modelValue"
    v-bind="getBindValue"
    @change="handleChange"
    :placeholder="placeholder"
    :clearable="clearable"
  >
    <el-option
      v-for="dict in selectOptions"
      :key="dict.value"
      :label="dict.label"
      :value="dict.value"
    />
  </el-select>
</template>

<script setup lang="ts">
import { useAttrs, computed } from 'vue'
import { getStrDictOptions, getIntDictOptions } from '@/utils/dict'
import { propTypes } from '@/utils/propTypes'

defineOptions({ name: 'DictSelector' })

const props = defineProps({
  modelValue: propTypes.any.def(''),
  placeholder: propTypes.string.def('请选择'),
  type: propTypes.string.def(''),
  clearable: propTypes.bool.def(false),
  valueType: propTypes.oneOf(['string', 'number']).def('string') // 新增属性，用于指定值类型
})

const getBindValue = computed(() => {
  const attrs = useAttrs()
  const obj = { ...attrs, ...props }
  return obj
})

// 定义事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: any): void
  (e: 'change', value: any): void
}>()
import type { StringDictDataType, NumberDictDataType } from '@/utils/dict'

const selectOptions = ref<Array<StringDictDataType | NumberDictDataType>>([])

watch(
  () => props.type,
  async (val: string) => {
    await nextTick()
    if (props.valueType === 'number') {
      selectOptions.value = await getIntDictOptions(val)
    } else {
      selectOptions.value = await getStrDictOptions(val)
    }
  },
  {
    immediate: true
  }
)

// 处理 change 事件
const handleChange = (value: any) => {
  emit('update:modelValue', value)
  emit('change', value)
}

// 允许父组件访问子组件属性
defineExpose({
  selectOptions: selectOptions
})
</script>
